<template>
  <div>
    <header-back :left-arrow="leftArrow" :fixed="fixed" :title="title" @onClickRight="onClickRight"></header-back>
    <!-- 主容器 -->

      <div class="lite-chatbox margin-top-46 margin-bottom-52 wrapper " id="">
        <div>
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <!-- cleft 左 -->
  <!--      <div class="cleft cmsg">-->
  <!--        <img class="headIcon radius"  src="./../../assets/img/head_3.png" />-->
  <!--        <span class="name">chenjunyu19</span>-->
  <!--        <span class="content">这是什么什么鬼？</span>-->
  <!--      </div>-->

  <!--      <div class="cright cmsg">-->
  <!--        <img class="headIcon radius"  src="./../../assets/img/head_2.jpeg" />-->
  <!--        <span class="name">SuperPaxxs</span>-->
  <!--        <span class="content">就是这个呀</span>-->
  <!--      </div>-->
          <div v-for="item in msgList" :class="item.acceptUserId==friendId ? 'cright cmsg' : 'cleft cmsg' " v-scroll>
            <img class="headIcon radius"  src="http://liuzhipin.gitee.io/images/img/head_2.jpeg" />
            <span class="name">{{item.acceptUserId==friendId ? nickname:friendNickname}}</span>
            <span class="content">{{item.msg}}</span>
          </div>
        </van-pull-refresh>
        </div>
      </div>

    <div class="talk-foot bg-nav vertical-center">
      <van-icon  class="iconfont icon_keyboard margin-left-10" color="#333333" size="23"></van-icon>
      <van-field
        v-model="message"
        rows="1"
        :autosize="autosize"
        type="textarea"
        :class="textareaStyle"
        @input="inputMessage()"
      />
      <van-icon  class="iconfont icon_face margin-left-10" color="#333333" size="22"></van-icon>
      <van-button type="primary" v-if="send" size="normal" class="margin-left-14 send-button" @click="sendMessage()">发送</van-button>
      <van-icon  class="iconfont icon_add margin-left-10" color="#333333" size="29" v-else></van-icon>
    </div>
  </div>
</template>

<script>
  import '@/assets/css/talking/litewebchat.css'
  import Util  from '@/assets/js/util/util.js'
  import signUtil  from '@/assets/js/util/sign.js'
  import md5 from 'js-md5'
  import HeaderBack from '../common/header-back'
  import talkingService from './talking-service.js'

  import Vue from 'vue';
  import { NavBar } from 'vant';

  import { Field } from 'vant';
  import { Button } from 'vant';
  import { PullRefresh } from 'vant';

  Vue.use(NavBar).use(Field).use(Button).use(PullRefresh);
  export default {
    name: 'talking',
    components:{
      HeaderBack
    },
    data(){
      return{
        zIndex:5,
        title:this.$route.params.nickname,
        //是否显示返回箭头
        leftArrow:false,
        // 是否固定顶部
        fixed:true,
        //发送的消息
        message:'',
        //发送消息体
        msgList:[

        ],
        autosize:{
          maxHeight: 92,
          minHeight: 28 ,
        },
        //发送按钮
        send:false,
        //用来判断左右显示
        friendId:this.$route.params.friendId,
        textareaStyle:'textarea',
        $user:null,
        isLoading: true,
        nickname:"",
        friendNickname:this.$route.params.nickname,
        page:1,
        pageSize:10
      }
    },
    directives: {
      scroll: {
        inserted(el) {
          el.scrollIntoView()
        }
      }
    },
    methods:{
      onClickRight:function () {
        // 父组件的这个方法被子组件调用1
        console.log('父组件的这个方法被子组件调用');
        // var mainActivity = plus.android.runtimeMainActivity();
        // var Settings= plus.android.importClass("android.provider.Settings");
        // alert(Settings.Secure.getString(mainActivity.getContentResolver(),Settings.Secure.ANDROID_ID));
        console.log('看看异常处理后有没有被调用');
      },
      inputMessage:function(){
        console.log('输入框内容变化触发');
        this.send=true;
        this.textareaStyle='textarea-send'
      },
      sendMessage:function () {
         let sendData = {
            //消息类型
            action:2,
              // 样式
              chatMsg:{
                sendUserId:this.$user.id,
                acceptUserId:this.$route.params.friendId,
                msg:this.message
            },
            //备用字段
            token:this.$user.token,
          }
          var params = signUtil.sortObjASCII(sendData);
          var sign = md5(params + 'signKey=' + this.$user.signKey);
          sendData.sign=sign;
          this.$websocket.dispatch('WEBSOCKET_SEND',JSON.stringify(sendData));
          let pushData={
            sendUserId:this.$user.id,
            acceptUserId:this.$route.params.friendId,
            msg:this.message
          }
          this.msgList.push(pushData);
          this.textareaStyle='textarea';
          this.send=false;
          this.message='';
      },

      //初始化历史记录
      getHistoryData:function () {
        let data={
          page:this.page,
          pageSize:this.pageSize,
          acceptUserId:this.$route.params.friendId
        }
        console.log('入参data====>',JSON.stringify(data));
        talkingService.getChatMessage(data).then(result =>{
          let res = result.data;
          console.log('result====>',JSON.stringify(result.data));
          if(res.code == '0'){
            if(res.result.length>0) {
              //reverse表示倒序 试了很多种情况这样才行
              this.msgList = res.result.reverse().concat(this.msgList);
            }else{
              this.page--;
            }
          }else{
            this.page--;
          }
        }).catch(err => {
          this.page--;
        }).finally(()=>{
        })

      },

      //下拉刷新
      onRefresh:function () {
        this.page++;
        this.getHistoryData();
        console.log("第"+this.page+"页");
        this.isLoading=false;
      }
    },
    computed: {
      getMessage(){
        return this.$websocket.state.getMessage;
      }
    },
    watch:{
      //监听消息 如果不为空就显示发送按钮
      message: {
        handler(newName, oldName) {
          if(newName!=''){
            this.textareaStyle='textarea-send';
            this.send=true;
          }else{
            this.textareaStyle='textarea';
            this.send=false;
          }
        },
        deep: true,
        immediate: true
      },
      getMessage(getMessage){
          console.log("监听到数据变化："+getMessage);
          var data= JSON.parse(getMessage);
          if(data.action!=2){
            console.log("只接受消息类型");
            return
          }
          let getData = {
            // 样式
            sendUserId:data.chatMsg.sendUserId,
            acceptUserId:data.chatMsg.acceptUserId,
            msg:data.chatMsg.msg
          }
          //表示是当前会话
          if(
            (data.chatMsg.sendUserId == this.$user.id && data.chatMsg.acceptUserId == this.$route.params.friendId)
            ||
            (data.chatMsg.acceptUserId == this.$user.id && data.chatMsg.sendUserId == this.$route.params.friendId)
            ){
            console.log("是当前会话!");
            this.msgList.push(getData);

          }else{
            //不是当前会话表示需要向会话列表中插入数据 标记已读和未读

          }
      },
    },
    mounted(){
      this.$user=JSON.parse(localStorage.getItem('user'));
      this.nickname=this.$user.nickname
      this.getHistoryData()
    },
  }
</script>

<style scoped>
  .wrapper{
    height: 100vh;
  }
  .lite-chatbox img.radius{
    border-radius: 5px;
  }
  .van-cell{
    padding: 0;
  }
  .textarea{
    /*width: 200px;*/
    width: 68%;
    margin-left: 5px;
  }

  .textarea-send{
    /*width: 200px;*/
    width: 60%;
    margin-left: 5px;
  }
  /*使用 scoped 如果无法改变 vant 中的样式  可以使用 >>> 深度选择器符号 */
  .textarea >>> .van-field__control{
    padding: 2px 2px;
    font-size: 14px;
  }

  .textarea >>> textarea{
    height: 32px!important;
  }
.send-button{
  height: 28px;
  width: 52px;
  line-height: 26px;
  padding: 0;
}
  .van-pull-refresh{
    height: 100%;
  }
</style>
